package cn.hwadee.muying.controller;


import cn.hwadee.muying.commons.base.BaseController;
import cn.hwadee.muying.commons.constant.ConstantRole;
import cn.hwadee.muying.commons.jqgrid.GridResult;
import cn.hwadee.muying.commons.page.MyPage;
import cn.hwadee.muying.commons.utils.FormUtils;
import cn.hwadee.muying.dto.Worker;
import cn.hwadee.muying.entity.User;
import cn.hwadee.muying.entity.WorkerInfo;
import cn.hwadee.muying.enums.Education;
import cn.hwadee.muying.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* <p>
* 职员 前端控制器
*
* </p>
*
* @author Mankind
* @since 2018-08-06
*/
@Controller
@RequestMapping("/sys/worker")
public class WorkerController extends BaseController {
    @Autowired
    private WorkerService workerService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private JobService jobService;
    @Autowired
    private WorkerLevelService workerLevelService;
    @ModelAttribute("worker")

    public Worker get(@RequestParam(required = false)Long id) throws Exception{
        if(id != null && id > 0){
            return workerService.selectById(id);
        }else{
            return new Worker();
        }
    }

    @RequiresPermissions("sys:worker:list")
    @RequestMapping(value="/list",produces = "text/html;charset=utf-8",method = RequestMethod.GET)
    public String list(Model model) throws Exception{
        model.addAttribute("educations",Education.values());
        model.addAttribute("workerLevels",workerLevelService.selectAll());
        return "/biz/worker/list";
    }

    @ResponseBody
    @RequiresPermissions("sys:worker:list")
    @RequestMapping(value="/list.json",produces = "application/json;charset=utf-8")
    public GridResult list(Integer entryStatus, Long workerLevel,Long education,String keyword) throws Exception{
        MyPage<Worker> page = getPage();
        page = workerService.list(page,getCurrentUser(),entryStatus,workerLevel,education,keyword);
        GridResult result = new GridResult(page.getCurrent(),page.getPages(),page.getCurrent(),page.getRecords());
        return result;
    }

    @RequiresPermissions("sys:worker:care")
    @RequestMapping(value="/care",produces = "text/html;charset=utf-8",method = RequestMethod.GET)
    public String care(Model model) throws Exception{
        return "/biz/worker/care";
    }

    @ResponseBody
    @RequiresPermissions("sys:worker:care")
    @RequestMapping(value="/care.json",produces = "application/json;charset=utf-8")
    public GridResult care(String keyword) throws Exception{
        MyPage<Worker> page = getPage();
        page = workerService.care(page,getCurrentUser(),keyword);
        GridResult result = new GridResult(page.getCurrent(),page.getPages(),page.getCurrent(),page.getRecords());
        return result;
    }

    @RequiresPermissions("sys:worker:upgrade")
    @RequestMapping(value="/upgrade",produces = "text/html;charset=utf-8",method = RequestMethod.GET)
    public String upgrade(Model model) throws Exception{
        return "/biz/worker/upgrade";
    }

    @ResponseBody
    @RequiresPermissions("sys:worker:upgrade")
    @RequestMapping(value="/upgrade.json",produces = "application/json;charset=utf-8")
    public GridResult upgrade(String keyword) throws Exception{
        MyPage<Worker> page = getPage();
        page = workerService.upgrade(page,getCurrentUser(),keyword);
        GridResult result = new GridResult(page.getCurrent(),page.getPages(),page.getCurrent(),page.getRecords());
        return result;
    }

    /**
     * 跳转添加/编辑职员界面
     * @param worker
     * @param model
     * @return
     * @throws Exception
     */
    @RequiresPermissions(value={"sys:worker:edit","sys:worker:add"},logical=Logical.OR)
    @RequestMapping(value = {"/edit","/add"}, produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String add(@ModelAttribute Worker worker,Model model) throws Exception{
        model.addAttribute("worker",worker);
        model.addAttribute("roles",roleService.getCommonRoles());
        model.addAttribute("jobs",jobService.selectAll());
        model.addAttribute("educations", Education.values());
        model.addAttribute("workerLevels",workerLevelService.selectAll());
        return "/biz/worker/edit";
    }

    /**
     * 处理更新职员的请求
     * @param worker
     * @return
     * @throws Exception
     */
    @RequiresPermissions(value={"sys:worker:edit","sys:worker:add"},logical=Logical.OR)
    @RequestMapping(value = "/edit", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(@ModelAttribute Worker worker){
        Map<String,Object> result = new HashMap();
        try {
        if(worker.getId() != null && worker.getId() > 0){
            workerService.updateById(worker);
        }else {
            User cUser=getCurrentUser();
            workerService.insert(worker,cUser);
        }
        result.put("status",200);
        result.put("msg","职员信息保存成功");
        }catch (Exception e){
        e.printStackTrace();
        result.put("status",500);
        result.put("msg","职员信息保存失败");
        }
        return result;
    }

    /**
     * 处理删除职员的请求
     * @param ids
     * @return
     * @throws Exception
     */
    @RequiresPermissions("sys:worker:delete")
    @RequestMapping(value = "/delete", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> delete(String ids){
        Map<String,Object> result = new HashMap();
        if(StringUtils.isNotEmpty(ids)){
            List<Long> idsArray = Arrays.asList(FormUtils.getIdsArray(ids));
            try {
                if(idsArray != null && idsArray.size() > 0){
                    workerService.deleteBatchIds(idsArray);
                    result.put("status",200);
                    result.put("msg","删除职员成功");
                }else {
                    result.put("status",500);
                    result.put("msg","请选择删除的职员");
                }
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg","删除职员失败");
            }
        }

        return result;
    }

    @RequiresPermissions("sys:worker:upload")
    @RequestMapping(value = "/excel", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String excelAdd(Model model) throws Exception {
        return "/biz/worker/excel";
    }

    @RequiresPermissions("sys:worker:upload")
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Map importWorker(@RequestParam("file") MultipartFile excel, Long orgId) throws Exception{
        Map<String,Object> result = new HashedMap();
        try{
            workerService.insertWorkerByExcel(excel.getInputStream(),orgId);
            result.put("code",0);
            result.put("status",200);
            result.put("msg","导入成功");
        }catch (Exception e){
            result.put("code",0);
            result.put("status",500);
            result.put("msg","导入失败，原因："+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @RequiresPermissions("sys:worker:download")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void exportAll(Model model, HttpServletResponse res) throws Exception{
        Resource resource = new ClassPathResource("template.xlsx");
        File file = resource.getFile();
        res.reset();
        res.setHeader("Cache-Control","no-cache, no-store, must-revalidate");
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        byte[] buff = new byte[1024];
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, i);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequiresPermissions("sys:worker:status")
    @RequestMapping(value="/status",produces = "text/html;charset=utf-8",method = RequestMethod.GET)
    public String status(Model model) throws Exception{
        model.addAttribute("educations",Education.values());
        model.addAttribute("workerLevels",workerLevelService.selectAll());
        return "/biz/worker/status";
    }

    @ResponseBody
    @RequiresPermissions("sys:worker:status")
    @RequestMapping(value="/status.json",produces = "application/json;charset=utf-8")
    public GridResult status(Long workerLevel,Long education,Integer free,String keyword) throws Exception{
        MyPage<Worker> page = getPage();
        page = workerService.status(page,getCurrentUser(),workerLevel,education,free,keyword);
        GridResult result = new GridResult(page.getCurrent(),page.getPages(),page.getCurrent(),page.getRecords());
        return result;
    }

    /**
     * 查看职员上岗信息界面
     * @param model
     * @return
     * @throws Exception
     */
    @RequiresPermissions(value={"sys:worker:check"},logical=Logical.OR)
    @RequestMapping(value = {"/check"}, produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String check(Model model) throws Exception{
        return "/biz/post/list";
    }
}
